/**
 * Created by Administrator on 2017/9/16.
 */

import Vue from 'vue'
import Vuex from 'vuex'
import products from './products'
import cart from './cart'
import * as types from './mutationNames'

Vue.use(Vuex)

//定义state
const state = {
}

//定义getters -- 相当于Store的计算属性
const getters = {
    productsInCart: function (state, getters) {
        return state.cart.added.map(item=>{return {
            product: getters.getProductById(item.id),
            count: item.count
        }});
    },
    total: function (state, getters) {
        return getters.productsInCart.reduce(function (total, item) {
            return total + item.product.price * item.count;
        }, 0.0)
    }
}

//Mutations
//作用：同步调用 store.commit 方法，更改 Vuex 的 store 中的状态的唯一方法
const mutations = {
}

//Actions
//作用：1.提交的是 mutation，而不是直接变更状态
//     2.可以包含任意异步操作
const actions = {
    addToCart: function ({commit}, product) {
        if(product.inventory > 0){
            commit(types.ADD_TO_CART, product.id)
        }
    },
    removeFromCart: function ({commit}, product) {
        commit(types.REMOVE_FROM_CART, product.id)
    },
    //payload: {product, count, oldcount}
    updateProductCount: function ({commit}, payload) {
        console.log('index.js UPDATE_PRODUCT_COUNT: ' )
        console.log(payload)
        if(payload.product.inventory + payload.oldcount >= payload.count) {
            commit(types.UPDATE_PRODUCT_COUNT, payload)
        }
    },
    clearCart: function ({commit}) {
        commit(types.CLEART_CART)
    }
}

//导出Store
export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions,
    modules:{
        products,
        cart
    }
});